from multiprocessing.pool import ThreadPool
from threading import Thread
from os.path import exists
from invidious import *
import operator
import time
import sys

from plugins.core.plugin import Plugin
from plugins.core.pluginvideo import PluginVideo
from plugins.core.pluginplaylist import PluginPlaylist

sys.path.append("..")
from src.vobjects.item import Item
from src.vobjects.video import Video
from src.vobjects.channel import Channel
from src.vobjects.playlist import Playlist
from src.vobjects.basechannel import BaseChannel

from src.utils import *
from src.config import Config
from src.history import History
from ui.progressbar import ProgressBar

class InvidiousLastVideos(Plugin):

    def __init__(self, history: History=History()):
        super().__init__(history=history)

        self.name = "Invidious: Last videos"
        self.is_query_required = False
        self.query_description = """"""

        self.config = Config()
        if exists(self.config.subs_path): self.SUBS_LIST = [i.strip('\n').split(',')[0] for i in open(self.config.subs_path)]
        else: self.SUBS_LIST = []
        self.subscriptions = list()
        self.sorted_sub_videos = list()

        self.flag = "-il"
        self.full_flag = "--ivlastvideos"
        self.flag_help = "show last videos from subscribed channels"
        self.flag_action = "store_true"

    def load_subscription(self, authorId=""):
        chn = self.invidious.get_channel(authorId)
        while chn == None:
            time.sleep(1)
            chn = self.invidious.get_channel(authorId)
        chn.convert(BaseChannel)
        item = chn.to_item()
        self.subscriptions.append(item)

        #==========> Update ProgressBar <==========#
        self.progressbar.increase_progress()
        self.progressbar.description = chn.author
        self.progressbar.big_description = self.invidious.get_working_mirror()+"/channel/"+authorId
        #==========================================#

    def load_subscriptions(self):
        if len(self.subscriptions) > 0 and not self.config.ReloadSubscribes: return
        self.subscriptions.clear()
        self.invidious.update_mirrors()

        #==========> Start ProgressBar <==========#
        self.progressbar = ProgressBar("Loading subscribes", 
                                       "", "", 0, len(self.SUBS_LIST), 40)
        th = Thread(target=self.progressbar.start_loop)
        th.start()
        #=========================================#

        pool = ThreadPool(processes=10)
        pool.map(self.load_subscription, self.SUBS_LIST)

        #==========> Kill ProgressBar <==========#
        self.progressbar.exit()
        #========================================#

        self.subscriptions = sort_channels_by_link_list(self.subscriptions, self.SUBS_LIST)      

    def get_last_videos(self, index: int=0):
        self.load_subscriptions()
        if len(self.sorted_sub_videos) == 0:
            items = []
            for sub in self.subscriptions:
                channel = sub.parent
                latestVideos = channel.latestVideos
                for video in latestVideos:
                    if video == None: continue
                    video.convert(Video)
                    video.url = self.invidious.get_working_mirror() + "/watch?v=" + video.videoId
                    inHistory = video.in_history(self.history)
                    item = video.to_item(inHistory=inHistory)
                    items.append(item)

            self.sorted_sub_videos = sorted(items, key=operator.attrgetter('parent.published'), reverse=True)

        return self.sorted_sub_videos

    def get_items_by_query(self, query: str=""):
        return list()

    def get_items(self):
        return self.get_last_videos()



if __name__ == "__main__":
    al = InvidiousSubscriptions()

    items = al.get_items_by_query(query="мастера меча онлайн")
    for item in items:
        print(item.title, item.parent.url)




